<!-- pendingReceiveOrderSelectDialog.vue -->
<template>
    <div class="pending-receive-order-page">
        <el-row>
            <el-col :span="24" style="padding-top: 24px; padding-left: 24px;">
                <el-form :inline="true" :model="filter" class="demo-form-inline">

                    <el-form-item label="客户">
                        <el-input v-model="filter.targetObjName" placeholder="客户名称" clearable />
                    </el-form-item>

                    <el-form-item label="进度状态">
                        <el-select v-model="filter.igProgressStateCode" placeholder="请选择" clearable>
                            <el-option label="未开始" :value="ProgressState.None.code" />
                            <el-option label="部分完成" :value="ProgressState.PartDone.code" />
                            <el-option label="全部完成" :value="ProgressState.AllDone.code" />
                        </el-select>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="handleSearch">查询</el-button>
                        <el-button @click="resetSearch">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="24" style="padding-top: 24px; padding-left: 24px;">              
                <el-button icon="Refresh" @click="refreshList">刷新列表</el-button>
            </el-col>
        </el-row>
        <el-row>

            <el-table v-loading="loading" :data="pendingOrderDataList"
                style="width: 100%; min-width: 600px; height: 100%;" @row-click="handleRowClick">
                <!---
          <el-table-column type="selection" :reserve-selection="true" width="55" :selectable="isSelectable"/>
          -->

                <el-table-column prop="docCode" label="单据编号" align="center" />

                <el-table-column prop="title" label="源单据标题" align="center" />

                <el-table-column label="客户" align="center">
                    <template #default="scope">
                        {{ scope.row.targetObject?.name || '-' }}
                    </template>
                </el-table-column>

                <el-table-column label="总金额" align="right">
                    <template #default="scope">
                        {{ formatCurrency(scope.row.totalMount) }}
                    </template>
                </el-table-column>

                <el-table-column label="已核销" align="right">
                    <template #default="scope">
                        {{ formatCurrency(scope.row.totalMount - scope.row.pendingPayMount) }}
                    </template>
                </el-table-column>

                <el-table-column label="待核销" align="right">
                    <template #default="scope">
                        {{ formatCurrency(scope.row.pendingPayMount) }}
                    </template>
                </el-table-column>

                <el-table-column label="进度状态" align="center">
                    <template #default="scope">
                        <el-tag v-if="scope.row.progressState.code === ProgressState.None.code">未开始</el-tag>
                        <el-tag v-else-if="scope.row.progressState.code === ProgressState.PartDone.code"
                            type="warning">部分完成</el-tag>
                        <el-tag v-else-if="scope.row.progressState.code === ProgressState.AllDone.code"
                            type="success">全部完成</el-tag>
                    </template>
                </el-table-column>

                <el-table-column label="操作" align="center">
                    <template #default="scope">
                        <el-link :underline="false" type="primary" @click.stop="showDetail(scope.row)">
                            详情
                        </el-link>
                    </template>
                </el-table-column>
            </el-table>

        </el-row>

        <div style="width: 80%; min-width: 600px; margin: 0 auto; padding: 0;">
            <pagination v-show="total > queryParams.pageNum" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="fetchPendingOrderData" />
        </div>
    </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import { FundUiAction } from '../../public/engine/uiAction/fundUiAction'
import { Definition } from '../../public/engine/common/definition'
import { DataPage } from '../../public/network/communicationConverter'
import { Util } from '../../public/utils/util'
import { PendingReceiveOrderFilter } from '../../public/engine/funds/pendingReceiveOrder'
import { ProgressState } from '../../public/engine/common/docDefinition'
import {deleteTargetObjectPendingReceiveOrderDataNetworkCache} from '../../public/network/api'
import { uiNavigation } from '../../public/views/uiEntrance/uiNavigation'

export default {
    name: 'receivable',

    emits: ['select'],
    data() {
        return {
            loading: false,
            pendingOrderDataList: [],
            total: 0,
            selectedItems: [],
            selectedPendingOrders: [], // 已选择的待收款单列表 上级UI 传入
            excludePendingOrders: [],
            filter: new PendingReceiveOrderFilter({}),
            queryParams: {
                pageNum: 1,
                pageSize: Definition.gDefualPageSize
            },
            targetObject: null,
            ProgressState,
            fundUiAction: new FundUiAction(),
        }
    },
    mounted() {
        this.fetchPendingOrderData()
    },
    methods: {
        async fetchPendingOrderData() {
            try {
                this.loading = true

                const res = await this.fundUiAction.getTargetObjectPendingReceiveOrderData({
                    pageInfo: new DataPage(this.queryParams.pageNum, 0, this.queryParams.pageSize),
                    filter: this.filter
                })

                if (res && res.data && res.data.dataList) {
                    this.pendingOrderDataList = res.data.dataList
                    this.total = res.data.pageInfo.total
                } else if (res.resErr) {
                    ElMessage.error('获取待收款单据数据失败: ' + res.resErr)
                }
            } catch (error) {
                console.error('获取待收款单据数据失败:', error)
                ElMessage.error('获取待收款单据数据失败')
            } finally {
                this.loading = false
            }
        },

        handleSearch() {
            this.queryParams.pageNum = 1
            this.fetchPendingOrderData()
        },

        refreshList(){
            deleteTargetObjectPendingReceiveOrderDataNetworkCache();                      
            this.fetchPendingOrderData();
        },

        resetSearch() {
            this.filter.clear()
            if (this.targetObject) {
                this.filter.targetObjId = this.targetObject.id
            }
            this.queryParams.pageNum = 1
            this.fetchPendingOrderData()
        },

        formatCurrency(value) {
            return Util.getFundString(value)
        },

        // 处理选择变化
        showDetailionChange(selection) {
            this.selectedItems = selection
        },
        // 单个选择待收款单
        showDetail(item) {
          uiNavigation.showReceivableOrderDetailPage(this.$router, item);
        },

        // 判断待收款单是否可选择
        isSelectable(row) {
            // 如果没有排除列表，则所有单据都可选择
            if (!this.excludePendingOrders || this.excludePendingOrders.length === 0) {
                return true;
            }

            // 检查当前单据是否在排除列表中
            return !this.excludePendingOrders.some(
                item => item.id === row.id
            );
        },

        rowClassName({ row }) {
            if (
                this.selectedPendingOrders.some(
                    item => item.id === row.id
                )
            ) {
                return 'already-selected-row';
            }
            return '';
        },

        handleRowClick(row) {
            // 可以在这里添加行点击事件的处理逻辑
        }
    }
}
</script>

<style scoped>
.pending-receive-order-page {
    padding-top: 0px;
    padding-left: 20px;
}

/* 已选择行的样式 */
:deep(.already-selected-row td.el-table__cell:first-child) {
    background: #d9f0ff !important;
}
</style>